#include "command.h"

int commandJudge(char *buf){                                                                                                      
    if(strcmp(buf, "cd") == 0){ 
        return 0;
    }else if(strcmp(buf, "ls") == 0){    
        return 0;
    }else if(strcmp(buf, "pwd") == 0){ 
        return 0;
    }else if(strcmp(buf, "mkdir") == 0){    
        return 0;
    }else if(strcmp(buf, "rmdir") == 0){    
        return 0;
    }else if(strcmp(buf, "puts") == 0){    
        return 0;
    }else if(strcmp(buf, "gets") == 0){    
        return 0;
    }else if(strcmp(buf, "remove") == 0){    
        return 0;
    }else if(strcmp(buf,"register")==0){
        return 0;
    }else if(strcmp(buf,"login")==0){
        return 0;
    }
    else{
        return -1; 
    }   
    return 0;
}


int commandManage(char *buf,int sockfd,char *salt){


    //清除换行符
    int len = strlen(buf);
    buf[len-1]='\0';

    char *results[2] = {NULL, NULL};

    int count = 0;
    char *token = strtok(buf, " ");

    while (token != NULL) {
        count++;
        // 只保存前两次切割结果
        if (count == 1) {
            results[0] = token;

        } else if (count == 2) {
            results[1] = token;
        }                                                                                                                         
        // 获取下一个分割块
        token = strtok(NULL, " ");
    }
    // 处理切割次数为0或者大于2的情况
    if (count == 0|| count >2) {
        printf("Invalid command\n");
        return 0;
    }
    // 是正常命令就传过去，否则无效
    int ret = commandJudge(results[0]);
    if(ret == 0){
        int size = 1;

        //保证传输的cd\register\login\mkdir\rmdir\register\login命令一定是两段，一段是非法命令
        int judge_length = 7;
        int judgement[judge_length];
        judgement[0] = strcmp(results[0],"cd");
        judgement[1] = strcmp(results[0],"register");
        judgement[2] = strcmp(results[0],"login");
        judgement[3] = strcmp(results[0],"rmdir");
        judgement[4] = strcmp(results[0],"mkdir");
        judgement[5] = strcmp(results[0],"register");
        judgement[6] = strcmp(results[0],"login");
        for(int i=0;i<judge_length;++i){
            if(count ==1&&judgement[i]==0){
                printf("Invalid command\n");
                return 0;
            }
        }
        if(count == 1){//只传输具体命令
            tlvSet(results, size, sockfd,salt);

        }else{
            //传输命令和后续指令
            size = sizeof(results)/sizeof(results[0]);
            tlvSet(results,size,sockfd,salt);

        }


    }else{
        printf("Invalid command\n");
        return 0;
    }

    return 0;
}


